package com.baidu.bos.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.impl.persistence.entity.UserEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baidu.bos.dao.IRoleDao;
import com.baidu.bos.dao.IUserDao;
import com.baidu.bos.domain.Role;
import com.baidu.bos.domain.User;
import com.baidu.bos.service.IUserService;
import com.baidu.bos.utils.MD5Utils;
import com.baidu.bos.utils.PageBean;
@Service
@Transactional
public class UserServiceImpl implements IUserService{
	@Resource
	private IUserDao userDao;
	@Resource
	private ProcessEngine processEngine;
	@Resource
	private IRoleDao roleDao;
	
	public User login(User model) {
		//首先将密码进行MD5加密
		String password = MD5Utils.md5(model.getPassword());
		List<User> list = userDao.findByNamedQuery("findByUsernamAndPassword", model.getUsername(),password);
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	public void editPassword(String password, String id) {
		//首先将密码进行Md5加密
		password = MD5Utils.md5(password);
		userDao.executeNamedQuery("editPassword", password,id);
	}

	public void save(User user, String[] roleIds) {
		//将密码进行md5加密
		String password = user.getPassword();
		password = MD5Utils.md5(password);
		user.setPassword(password);
		userDao.save(user);//持久状态
		//保存用户的时候,保存activiti中的user信息
		org.activiti.engine.identity.User actUser = new UserEntity();
		actUser.setId(user.getId());
		processEngine.getIdentityService().saveUser(actUser);
		
		if (roleIds != null && roleIds.length > 0) {
			for (String roleId : roleIds) {
				//Role role = new Role(roleId);
				Role role = roleDao.findById(roleId);
				user.getRoles().add(role);
				processEngine.getIdentityService().createMembership(actUser.getId(), role.getName());
			}
		}
		
	}

	public void pageQuery(PageBean pageBean) {
		userDao.pageQuery(pageBean);
	}
	//删除用户,需要写删除用户之间的关联关系
	public void delete(String userIds) {
		String[] uIds = userIds.split(",");
		for (String uId : uIds) {
			//注意:这里需要先从数据库查询到持久化对象,而不是new一个出来
			User user = userDao.findById(uId);
			userDao.delete(user);
		}
	}

}
